package system.parser;

import java.util.Map;

import object.model.JavaVariables;
import object.model.MySQLData;
import object.model.MySQL_TableDesc;
import system.Sys_Config;

public class Sys_SQL2JavaTypeParser {
	
	private static Map<String, MySQLData> mdr = Sys_Config.MYSQL_DATA_REL;
	
	public JavaVariables parse(MySQL_TableDesc mySqlTableDesc){
		JavaVariables j = null;
		String pureType = this.getPureType(mySqlTableDesc.getType());
		MySQLData data = mdr.get(pureType);
		String cdn = this.getCondiction(mySqlTableDesc);
		try{			
			j = new JavaVariables(data.getJavaClassFullName(),mySqlTableDesc.getField(), mySqlTableDesc.getType(), cdn);
			if(mySqlTableDesc.getKey().equalsIgnoreCase("PRI")){
				j.setPrimaryKey(true);
			}
		}catch (Exception e){
			e.printStackTrace();
		}		
		return j;
	}
	
	private String getCondiction(MySQL_TableDesc desc){
		String cdn = "";
		if(desc.getNull().equalsIgnoreCase("YES")){//allow null
			if(desc.getDefault() == null){
				cdn = "DEFAULT NULL";
			}else{
				if(desc.getDefault().equalsIgnoreCase("CURRENT_TIMESTAMP")){
					cdn = "DEFAULT " + desc.getDefault();
				}else{
					cdn = "DEFAULT '" + desc.getDefault() + "'";
				}
			}
		}else{
			cdn = "NOT NULL";
		}
		if(!desc.getExtra().equalsIgnoreCase("")){
			if(desc.getExtra().contains("on update CURRENT_TIMESTAMP")){
				cdn = "NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP";
			}else{
				cdn += " " + desc.getExtra();
			}			
		}
		return cdn;
	}
	
	private String getPureType(String rawtype){
		String pt = null;
		rawtype = rawtype.replace("zerofill", "").trim();
		if(rawtype.contains("(")){
			pt = rawtype.split("\\(")[0];
			try{
				String tmp =  rawtype.split("\\)")[1];
				pt += tmp;
			}catch(Exception e){
				//nothing
			}
		}else{
			pt = rawtype;
		}
		return pt;
	}
	
}
